import express from "express";
import { PrismaClient, Prisma } from ".prisma/client";
import { Result, Time } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

/** 获取客户列表 */
router.get("/search", async (req, res) => {
   const { form, laypage }: Client.Search = req.query as any;
   /** 查询条件 */
   const where: Prisma.clientWhereInput = {
      AND: [
         { OR: form.name ? [{ name: { search: `"${form.name}"` } }, { phone: { search: `${form.name}*` } }] : [] },
         Boolean(form.sex) ? { sex: form.sex } : {},
         Boolean(form.status) ? { status: form.status } : {},
         form.hasPhone ? {} : { phone: { not: null } },
         {
            AND: form.time
               ? [{ created_time: { gte: new Date(form.time[0]) } }, { created_time: { lte: new Date(form.time[1]) } }]
               : {}
         }
      ]
   };

   const total = await prisma.client.count({ where });
   const userList = await prisma.client.findMany({
      select: {
         id: true,
         created_time: true,
         head_img: true,
         phone: true,
         sex: true,
         sign: true,
         status: true,
         name: true
      },
      where,
      skip: (laypage.pageNum - 1) * laypage.pageSize,
      take: laypage.pageSize * 1,
      orderBy: {
         created_time: "desc"
      }
   });

   const list = userList.map(item => {
      return {
         ...item,
         // phone: phoneEncryption(item.phone),
         pay_info: [],
         created_time: Time.Format(item.created_time)
      };
   });

   res.send(
      Result.OK({
         list,
         total: Number(total),
         pageNum: Number(laypage.pageNum),
         pageSize: Number(laypage.pageSize)
      })
   );
});

export const client = router;
